package www.dashu.com.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import www.dashu.com.api.ResultCode;
import www.dashu.com.constant.AuthConstant;
import www.dashu.com.domain.TokenUser;
import www.dashu.com.exception.Asserts;
import www.dashu.com.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class AdminService
{
    @Autowired
    private HttpServletRequest request;
    @Autowired
    SysUserService userService;
    @Autowired
    AdminCacheService adminCacheService;

    public SysUser getCurrentAdmin() {
        String userStr = request.getHeader(AuthConstant.USER_TOKEN_HEADER);
        if(StrUtil.isEmpty(userStr)){
            Asserts.fail(ResultCode.UNAUTHORIZED);
        }
        TokenUser userDto = JSONUtil.toBean(userStr, TokenUser.class);
        SysUser admin = adminCacheService.getAdmin(userDto.getId());
        if(admin!=null){
            return admin;
        }else{
            admin = userService.findById(userDto.getId()).get();
            adminCacheService.setAdmin(admin);
            return admin;
        }
    }

}
